package util

import (
	"github.com/Unknwon/goconfig"
	"github.com/siddontang/go-log/log"
)

type MysqlConfig struct {
	SlaveId uint32
	Host string
	Port uint16
	Username string
	Password string
}

//type kafkaConfig struct {
//	Urls []string
//}

type dataConfig struct {
	Dir string
	LogPosFilePath string
}

type appConfig struct {
	AppName string
	DataConfig dataConfig
	MysqlConfig MysqlConfig
	//KafkaConfig kafkaConfig
}

var config *appConfig

func GetAppConfig() *appConfig  {
	if config!=nil{
		return config
	}
	config,_ = ReloadAppConfig()
	return config
}

func ReloadAppConfig() (*appConfig,error) {
	cfg, err := goconfig.LoadConfigFile("./config/app.conf")
	if err!=nil{
		log.Error(err)
		return nil,err
	}
	appname, _ := cfg.GetValue(goconfig.DEFAULT_SECTION,"appname")

	slaveIdStr, _ := cfg.GetValue(goconfig.DEFAULT_SECTION,"mysql.slave_id")
	slaveId,_:= StrToUint32(slaveIdStr)
	host, _ := cfg.GetValue(goconfig.DEFAULT_SECTION,"mysql.host")
	portStr, _ := cfg.GetValue(goconfig.DEFAULT_SECTION,"mysql.port")
	port,_:=StrToUint16(portStr)
	username, _ := cfg.GetValue(goconfig.DEFAULT_SECTION,"mysql.username")
	password, _ := cfg.GetValue(goconfig.DEFAULT_SECTION,"mysql.password")
	mysqlConfig:= MysqlConfig{slaveId,host,port,username,password}

	//kafkaUrlsListStr, _ := cfg.GetValue(goconfig.DEFAULT_SECTION,"kafka.urls")
	//kafkaConfig:=kafkaConfig{strings.Split(kafkaUrlsListStr, ",")}

	dataDir, _ := cfg.GetValue(goconfig.DEFAULT_SECTION,"data.dir")
	dataConfig:=dataConfig{dataDir,dataDir+"/sync.pos"}

	config = new(appConfig)
	config.AppName = appname
	config.DataConfig = dataConfig

	config.MysqlConfig = mysqlConfig
	//config.KafkaConfig = kafkaConfig

	return config,nil
}
